package com.chzye.xhanddemos

import android.Manifest
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.content.ContextCompat
import com.chzye.xhanddemos.ui.theme.XhandDemosTheme
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.shoujing.autoaiui.AiuiManager
/**
 * 主活动类
 * 
 * 功能包括：
 * 1. 权限管理（基础权限和USB权限）
 * 2. USB设备检测和管理
 * 3. 红外设备识别和连接
 * 4. 用户友好的错误处理和设备诊断
 * 
 * 参考 rokid_apg_xhands 项目的 TemplateInfraGdCameraActivity 实现
 */
class MainActivity : ComponentActivity() {

    companion object {
        private const val ACTION_USB_PERMISSION = "com.chzye.xhanddemos.USB_PERMISSION"
        private const val TAG = "MainActivity"
    }

    private val requiredPermissions = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )

    private lateinit var usbManager: UsbManager
    private var pendingGdJavaStart = false
    
    // 现代权限请求处理器
    private val permissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        if (allGranted) {
            Toast.makeText(this, "基础权限已授予", Toast.LENGTH_SHORT).show()
            checkUsbPermissionAndStart()
        } else {
            Toast.makeText(this, "需要相机和存储权限才能使用红外功能", Toast.LENGTH_LONG).show()
        }
    }

    private val usbReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            when (action) {
                ACTION_USB_PERMISSION -> {
                    synchronized(this) {
                        val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                         device?.let {
                             android.util.Log.d(TAG, "USB权限已授予，设备: ${it.deviceName}")
                             Toast.makeText(context, "✅ USB权限已授予，正在启动红外功能...", Toast.LENGTH_SHORT).show()
                             // 延迟一下让用户看到成功提示
                             android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                                 startGdJavaActivityDirectly()
                             }, 500)
                         }
                     } else {
                         android.util.Log.w(TAG, "USB权限被拒绝")
                         device?.let {
                             Toast.makeText(context, "❌ USB权限被拒绝", Toast.LENGTH_SHORT).show()
                         }
                         // USB权限被拒绝，显示专门的对话框
                         showUsbPermissionDeniedDialog()
                     }
                        pendingGdJavaStart = false
                    }
                }
                UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
                    val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
                    device?.let {
                        android.util.Log.d(TAG, "USB设备已连接: ${it.deviceName}")
                        if (isInfraredDevice(it)) {
                            Toast.makeText(context, "检测到红外设备连接", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                UsbManager.ACTION_USB_DEVICE_DETACHED -> {
                    val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
                    device?.let {
                        android.util.Log.d(TAG, "USB设备已断开: ${it.deviceName}")
                        if (isInfraredDevice(it)) {
                            Toast.makeText(context, "红外设备已断开连接", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 初始化USB管理器
        usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        
        // 注册USB相关广播接收器
        val filter = IntentFilter().apply {
            addAction(ACTION_USB_PERMISSION)
            addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
            addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
        }
        registerReceiver(usbReceiver, filter)

        enableEdgeToEdge()
        setContent {
            XhandDemosTheme {
                MainScreen(
                    onLothalClick = {
                        requestLothalPermissions()
                    },
                    onGDJavaClick = {
                        startGdJavaActivity()
                    },
                    onAiuiTestClick = {
                        testAiuiManager()
                    }
                )
            }
        }
    }

    private fun requestLothalPermissions() {
        XXPermissions.with(this)
            .permission(Permission.RECORD_AUDIO)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (allGranted) {
                        Toast.makeText(this@MainActivity, "麦克风权限已授予", Toast.LENGTH_SHORT).show()
                        LothalManager.start(this@MainActivity)
                    } else {
                        Toast.makeText(this@MainActivity, "麦克风权限未授予", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        Toast.makeText(this@MainActivity, "权限被永久拒绝，请手动授予", Toast.LENGTH_LONG).show()
                        XXPermissions.startPermissionActivity(this@MainActivity, permissions)
                    } else {
                        Toast.makeText(this@MainActivity, "权限被拒绝", Toast.LENGTH_SHORT).show()
                    }
                }
            })
    }



    private fun startGdJavaActivity() {
        // 首先检查基础权限
        if (!checkBasicPermissions()) {
            requestBasicPermissions()
            return
        }
        
        // 检查USB权限并启动Activity
        checkUsbPermissionAndStart()
    }
    
    private fun startGdJavaActivityDirectly() {
        val intent = Intent(this, GdActivityJava::class.java)
        startActivity(intent)
    }

    private fun testAiuiManager() {
        try {
            val callback = object : com.shoujing.autoaiui.AiuiManagerCallback {

                override fun xfResult(p0: String?) {

                }
            }
            
            val aiuiManager = AiuiManager.getInstance(this, callback)
            val packageName = applicationInfo.packageName
            aiuiManager.skipKeyByPackageName(packageName)

        } catch (e: Exception) {
            Toast.makeText(this, "调用AiuiManager失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }

    private fun checkBasicPermissions(): Boolean {
        return requiredPermissions.all { permission ->
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
        }
    }
    
    private fun requestBasicPermissions() {
        permissionLauncher.launch(requiredPermissions)
    }
    
    private fun checkUsbPermissionAndStart() {
        val device = findInfraredDevice()
        if (device != null) {
            if (usbManager.hasPermission(device)) {
                val deviceType = if (isInfraredDevice(device)) "红外设备" else "USB设备"
                Toast.makeText(this, "检测到${deviceType}，启动功能", Toast.LENGTH_SHORT).show()
                startGdJavaActivityDirectly()
            } else {
                // 检测到设备但未授权，显示权限申请对话框
                showUsbPermissionRequestDialog(device)
            }
        } else {
            // 显示设备未找到对话框
            showDeviceNotFoundDialog()
        }
    }
    
    private fun findInfraredDevice(): UsbDevice? {
        val deviceList = usbManager.deviceList
        
        android.util.Log.d(TAG, "=== 开始查找USB设备 ===")
        android.util.Log.d(TAG, "当前连接设备数量: ${deviceList.size}")
        
        if (deviceList.isEmpty()) {
            android.util.Log.w(TAG, "没有检测到任何USB设备")
            return null
        }
        
        // 先列出所有设备的基本信息
        android.util.Log.d(TAG, "所有连接的USB设备:")
        deviceList.values.forEachIndexed { index, device ->
            android.util.Log.d(TAG, "设备${index + 1}: ${device.deviceName}")
            android.util.Log.d(TAG, "  - 类别: ${device.deviceClass}")
            android.util.Log.d(TAG, "  - VID: 0x${device.vendorId.toString(16)}")
            android.util.Log.d(TAG, "  - PID: 0x${device.productId.toString(16)}")
            android.util.Log.d(TAG, "  - 接口数量: ${device.interfaceCount}")
        }
        
        // 支持所有USB设备，返回第一个设备
        val firstDevice = deviceList.values.firstOrNull()
        if (firstDevice != null) {
            android.util.Log.d(TAG, "🎯 选择USB设备: ${firstDevice.deviceName}")
            android.util.Log.d(TAG, "设备类型: ${if (isInfraredDevice(firstDevice)) "红外设备" else "普通USB设备"}")
        } else {
            android.util.Log.w(TAG, "❌ 未找到任何USB设备")
        }
        
        android.util.Log.d(TAG, "=== USB设备查找结束 ===")
        return firstDevice
    }
    
    private fun isInfraredDevice(device: UsbDevice): Boolean {
        val vendorId = device.vendorId
        val productId = device.productId
        val deviceName = device.deviceName?.lowercase() ?: ""
        val deviceClass = device.deviceClass
        
        android.util.Log.d(TAG, "检查设备: ${device.deviceName}, 类别: $deviceClass, VID: 0x${vendorId.toString(16)}, PID: 0x${productId.toString(16)}")
        
        // 1. 检查设备类别
        when (deviceClass) {
            14 -> { // UVC设备类（Video Class）
                android.util.Log.d(TAG, "✓ 通过UVC设备类识别红外设备: ${device.deviceName}")
                return true
            }
            239 -> { // 红外设备类（Miscellaneous Device Class）
                android.util.Log.d(TAG, "✓ 通过红外设备类识别红外设备: ${device.deviceName}")
                return true
            }
            9 -> { // Hub设备类，某些红外设备可能显示为此类
                android.util.Log.d(TAG, "检测到Hub设备类，继续其他检查: ${device.deviceName}")
            }
            0 -> { // 未定义设备类，某些红外设备可能显示为此类
                android.util.Log.d(TAG, "检测到未定义设备类，继续其他检查: ${device.deviceName}")
            }
        }
        
        // 2. 检查厂商ID和产品ID（扩展的红外模组厂商列表）
        val knownInfraredVendors = listOf(
            0x1e4e, // 海康威视
            0x2bdf, // 大华
            0x0547, // Anchor Chips
            0x1871, // Aveo Technology
            0x05a3, // ARC International
            0x046d, // Logitech（某些型号）
            0x0c45, // Microdia
            0x1b3f, // Generalplus Technology
            0x0bda, // Realtek（某些USB摄像头芯片）
            0x1bcf, // Sunplus Innovation Technology
            0x18ec, // Arkmicro Technologies
            0x0ac8, // Z-Star Microelectronics
            0x174f, // Syntek
            0x1908, // GEMBIRD
            0x1d6b, // Linux Foundation（某些情况下）
            0x2207, // Fuzhou Rockchip Electronics
            0x0525, // Netchip Technology（某些开发板）
            // 可以根据实际使用的红外模组添加更多VID
        )
        
        if (vendorId in knownInfraredVendors) {
            android.util.Log.d(TAG, "✓ 通过已知厂商VID识别红外设备: VID=0x${vendorId.toString(16)}, PID=0x${productId.toString(16)}")
            return true
        }
        
        // 3. 检查设备名称关键词（扩展关键词列表）
        val infraredKeywords = listOf(
            "infrared", "thermal", "ir", "flir", "seek", "guide", "gd",
            "camera", "webcam", "usb camera", "video", "capture",
            "thermal camera", "ir camera", "night vision",
            "temperature", "heat", "thermo", "imaging"
        )
        
        for (keyword in infraredKeywords) {
            if (deviceName.contains(keyword)) {
                android.util.Log.d(TAG, "✓ 通过关键词'$keyword'识别红外设备: ${device.deviceName}")
                return true
            }
        }
        
        // 4. 检查接口描述符（如果设备有多个接口）
        try {
            for (i in 0 until device.interfaceCount) {
                val usbInterface = device.getInterface(i)
                val interfaceClass = usbInterface.interfaceClass
                val interfaceSubclass = usbInterface.interfaceSubclass
                
                // 检查是否为视频设备接口
                if (interfaceClass == 14) { // Video Class
                    android.util.Log.d(TAG, "✓ 通过接口类别识别红外设备: 接口$i 为视频类")
                    return true
                }
                
                // 检查是否为厂商自定义接口
                if (interfaceClass == 255) { // Vendor Specific
                    android.util.Log.d(TAG, "检测到厂商自定义接口: 接口$i")
                }
            }
        } catch (e: Exception) {
            android.util.Log.w(TAG, "检查接口描述符时出错: ${e.message}")
        }
        
        // 5. 宽松模式：如果设备名称包含"camera"或"video"，也认为可能是红外设备
        if (deviceName.contains("camera") || deviceName.contains("video") || deviceName.contains("webcam")) {
            android.util.Log.d(TAG, "⚠️ 宽松模式识别可能的红外设备: ${device.deviceName}")
            return true
        }
        
        android.util.Log.d(TAG, "✗ 未识别为红外设备: ${device.deviceName}")
        return false
    }
    
    private fun requestUsbPermission(device: UsbDevice) {
        pendingGdJavaStart = true
        val permissionIntent = PendingIntent.getBroadcast(
            this, 0, Intent(ACTION_USB_PERMISSION), 
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0
        )
        usbManager.requestPermission(device, permissionIntent)
        Toast.makeText(this, "正在请求USB权限...", Toast.LENGTH_SHORT).show()
    }
    
    /**
     * 显示设备未找到对话框
     * 参考 TemplateInfraGdCameraActivity 的实现
     */
    private fun showDeviceNotFoundDialog() {
         AlertDialog.Builder(this)
             .setTitle("红外设备未找到")
             .setMessage(
                 ("未检测到红外模组设备，请检查：\n\n" +
                 "1. 确认红外模组已正确连接到设备\n" +
                 "2. 检查USB连接线是否正常\n" +
                 "3. 确认设备支持USB Host模式\n" +
                 "4. 重新插拔红外模组\n" +
                 "5. 重启应用后重试\n\n" +
                 "您可以选择继续使用应用（无红外功能）、查看设备信息或退出应用。") as CharSequence
             )
             .setPositiveButton("继续使用") { _, _ ->
                 // 继续启动应用，但没有红外功能
                 Toast.makeText(this, "启动应用（无红外功能）", Toast.LENGTH_SHORT).show()
                 startGdJavaActivityDirectly()
             }
             .setNegativeButton("退出应用") { _, _ ->
                 // 退出应用
                 finish()
             }
             .setNeutralButton("设备信息") { _, _ ->
                 // 显示设备信息对话框
                 showDeviceInfoDialog()
             }
             .setCancelable(false)
             .show()
     }
    
    /**
     * 显示USB权限申请对话框（检测到设备但未授权时）
     */
    private fun showUsbPermissionRequestDialog(device: UsbDevice) {
        val isInfrared = isInfraredDevice(device)
        val deviceType = if (isInfrared) "红外设备" else "USB设备"
        
        AlertDialog.Builder(this)
            .setTitle("发现${deviceType}")
            .setMessage(
                ("检测到${deviceType}：${device.deviceName}\n\n" +
                "设备信息：\n" +
                "• 厂商ID: 0x${device.vendorId.toString(16)}\n" +
                "• 产品ID: 0x${device.productId.toString(16)}\n\n" +
                "需要授予USB权限才能使用此设备。\n" +
                "点击'授权'将弹出系统权限对话框。") as CharSequence
            )
            .setPositiveButton("授权") { _, _ ->
                requestUsbPermission(device)
            }
            .setNegativeButton("跳过此设备") { _, _ ->
                Toast.makeText(this, "启动应用（跳过此设备）", Toast.LENGTH_SHORT).show()
                startGdJavaActivityDirectly()
            }
            .setNeutralButton("设备信息") { _, _ ->
                showDeviceInfoDialog()
            }
            .setCancelable(false)
            .show()
    }
    
    /**
     * 显示USB权限被拒绝对话框
     */
    private fun showUsbPermissionDeniedDialog() {
        AlertDialog.Builder(this)
            .setTitle("USB权限被拒绝")
            .setMessage(
                ("红外模组需要USB权限才能正常工作。\n\n" +
                "解决方案：\n" +
                "1. 点击'重新申请'重新弹出权限对话框\n" +
                "2. 在权限对话框中选择'允许'或'始终允许'\n" +
                "3. 如果没有弹出对话框，请检查设备连接\n" +
                "4. 部分设备需要在开发者选项中启用USB调试\n\n" +
                "您也可以选择无红外模式继续使用应用。") as CharSequence
            )
            .setPositiveButton("重新申请") { _, _ ->
                Toast.makeText(this, "重新检测设备并申请权限...", Toast.LENGTH_SHORT).show()
                checkUsbPermissionAndStart()
            }
            .setNegativeButton("无红外模式") { _, _ ->
                Toast.makeText(this, "启动应用（无红外功能）", Toast.LENGTH_SHORT).show()
                startGdJavaActivityDirectly()
            }
            .setNeutralButton("设备信息") { _, _ ->
                showDeviceInfoDialog()
            }
            .show()
     }
     
     /**
       * 显示设备信息对话框（调试用）
       */
      private fun showDeviceInfoDialog() {
          val deviceList = usbManager.deviceList
          val deviceInfo = StringBuilder()
          var unauthorizedInfraredDevice: UsbDevice? = null
          
          if (deviceList.isEmpty()) {
              deviceInfo.append("未检测到任何USB设备\n\n")
              deviceInfo.append("可能原因：\n")
              deviceInfo.append("• 没有连接USB设备\n")
              deviceInfo.append("• 设备不支持USB Host模式\n")
              deviceInfo.append("• USB连接线故障")
          } else {
              deviceInfo.append("=== USB设备详细信息 ===\n\n")
              deviceInfo.append("检测到 ${deviceList.size} 个USB设备:\n\n")
              var hasInfraredDevice = false
              deviceList.values.forEachIndexed { index, device ->
                  val isInfrared = isInfraredDevice(device)
                  val recognitionReason = getDeviceRecognitionReason(device)
                  if (isInfrared) {
                      hasInfraredDevice = true
                      if (!usbManager.hasPermission(device)) {
                          unauthorizedInfraredDevice = device
                      }
                  }
                  
                  deviceInfo.append("📱 设备 ${index + 1}${if (isInfrared) " [红外设备]" else " [USB设备]"}:\n")
                  deviceInfo.append("  名称: ${device.deviceName}\n")
                  deviceInfo.append("  设备类别: ${device.deviceClass} ${getDeviceClassDescription(device.deviceClass)}\n")
                  deviceInfo.append("  厂商ID: 0x${device.vendorId.toString(16)} (${device.vendorId})\n")
                  deviceInfo.append("  产品ID: 0x${device.productId.toString(16)} (${device.productId})\n")
                  deviceInfo.append("  接口数量: ${device.interfaceCount}\n")
                  
                  // 显示接口信息
                  if (device.interfaceCount > 0) {
                      deviceInfo.append("  接口详情:\n")
                      try {
                          for (i in 0 until device.interfaceCount) {
                              val usbInterface = device.getInterface(i)
                              deviceInfo.append("    接口$i: 类别=${usbInterface.interfaceClass}, 子类=${usbInterface.interfaceSubclass}\n")
                          }
                      } catch (e: Exception) {
                          deviceInfo.append("    无法读取接口信息: ${e.message}\n")
                      }
                  }
                  
                  deviceInfo.append("  权限状态: ${if (usbManager.hasPermission(device)) "✅ 已授权" else "❌ 未授权"}\n")
                  deviceInfo.append("  设备类型: ${if (isInfrared) "✅ 红外设备" else "✅ USB设备"}\n")
                  
                  if (recognitionReason.isNotEmpty()) {
                      deviceInfo.append("  识别原因: $recognitionReason\n")
                  }
                  
                  deviceInfo.append("\n")
              }
              
              if (!hasInfraredDevice) {
                  deviceInfo.append("⚠️ 未发现红外设备（但可能有其他USB设备）\n")
                  deviceInfo.append("应用支持所有USB设备")
              } else if (unauthorizedInfraredDevice != null) {
                  deviceInfo.append("💡 发现未授权的设备\n")
                  deviceInfo.append("点击'申请权限'按钮来授权设备")
              }
          }
          
          val dialog = AlertDialog.Builder(this)
              .setTitle("USB设备信息")
              .setMessage(deviceInfo.toString() as CharSequence)
              .setPositiveButton("关闭", null)
              .setNegativeButton("重新检测") { _, _ ->
                  Toast.makeText(this, "重新检测USB设备...", Toast.LENGTH_SHORT).show()
                  checkUsbPermissionAndStart()
              }
          
          // 如果有未授权的设备，添加申请权限按钮
          if (unauthorizedInfraredDevice != null) {
              dialog.setNeutralButton("申请权限") { _, _ ->
                  Toast.makeText(this, "正在申请USB权限...", Toast.LENGTH_SHORT).show()
                  requestUsbPermission(unauthorizedInfraredDevice)
              }
          }
          
          dialog.show()
      }
      
      /**
       * 获取设备识别原因
       */
      private fun getDeviceRecognitionReason(device: UsbDevice): String {
          val reasons = mutableListOf<String>()
          val vendorId = device.vendorId
          val productId = device.productId
          val deviceName = device.deviceName?.lowercase() ?: ""
          val deviceClass = device.deviceClass
          
          // 检查设备类别
          when (deviceClass) {
              14 -> reasons.add("UVC设备类(14)")
              239 -> reasons.add("红外设备类(239)")
              9 -> reasons.add("Hub设备类(9)")
              0 -> reasons.add("未定义设备类(0)")
          }
          
          // 检查厂商ID
          val knownInfraredVendors = mapOf(
              0x1e4e to "海康威视",
              0x2bdf to "大华",
              0x0547 to "Anchor Chips",
              0x1871 to "Aveo Technology",
              0x05a3 to "ARC International",
              0x046d to "Logitech",
              0x0c45 to "Microdia",
              0x1b3f to "Generalplus Technology",
              0x0bda to "Realtek",
              0x1bcf to "Sunplus Innovation",
              0x18ec to "Arkmicro Technologies",
              0x0ac8 to "Z-Star Microelectronics",
              0x174f to "Syntek",
              0x1908 to "GEMBIRD",
              0x1d6b to "Linux Foundation",
              0x2207 to "Fuzhou Rockchip",
              0x0525 to "Netchip Technology"
          )
          
          knownInfraredVendors[vendorId]?.let {
              reasons.add("已知厂商: $it")
          }
          
          // 检查设备名称关键词
          val infraredKeywords = listOf(
              "infrared", "thermal", "ir", "flir", "seek", "guide", "gd",
              "camera", "webcam", "usb camera", "video", "capture",
              "thermal camera", "ir camera", "night vision",
              "temperature", "heat", "thermo", "imaging"
          )
          
          for (keyword in infraredKeywords) {
              if (deviceName.contains(keyword)) {
                  reasons.add("关键词: '$keyword'")
                  break
              }
          }
          
          // 检查接口类别
          try {
              for (i in 0 until device.interfaceCount) {
                  val usbInterface = device.getInterface(i)
                  if (usbInterface.interfaceClass == 14) {
                      reasons.add("视频接口类别")
                      break
                  }
              }
          } catch (e: Exception) {
              // 忽略接口检查错误
          }
          
          return if (reasons.isEmpty()) "未匹配任何识别条件" else reasons.joinToString(", ")
      }
      
      /**
       * 获取设备类别描述
       */
      private fun getDeviceClassDescription(deviceClass: Int): String {
          return when (deviceClass) {
              0 -> "(未定义)"
              1 -> "(音频)"
              2 -> "(通信)"
              3 -> "(人机接口)"
              5 -> "(物理)"
              6 -> "(图像)"
              7 -> "(打印机)"
              8 -> "(存储)"
              9 -> "(Hub)"
              10 -> "(数据)"
              11 -> "(智能卡)"
              13 -> "(安全)"
              14 -> "(视频)"
              15 -> "(医疗)"
              220 -> "(诊断)"
              224 -> "(无线)"
              239 -> "(杂项)"
              254 -> "(应用)"
              255 -> "(厂商自定义)"
              else -> "(未知类别)"
          }
      }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        when (event.keyCode) {
            KeyEvent.KEYCODE_PAGE_DOWN -> {
                Log.i("TAG", "onKeyDown: 1111")
                //拦截事件
                return true
            }
            KeyEvent.KEYCODE_PAGE_UP -> {
                Log.i("TAG", "onKeyDown: 2222")
                return true
            }
        }
        return super.dispatchKeyEvent(event)
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            unregisterReceiver(usbReceiver)
        } catch (e: Exception) {
            // 忽略重复注销的异常
        }
        LothalManager.stop()
    }
}

@Composable
fun MainScreen(onLothalClick: () -> Unit, onGDJavaClick: () -> Unit, onAiuiTestClick: () -> Unit) {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Button(onClick = onLothalClick) {
            Text("Start Lothal Manager")
        }
        Button(onClick = onGDJavaClick) {
            Text("Start GD Activity (Java1)")
        }
        Button(onClick = onAiuiTestClick) {
            Text("Test AiuiManager")
        }
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    XhandDemosTheme {
        MainScreen(
            onLothalClick = {},
            onGDJavaClick = {},
            onAiuiTestClick = {}
        )
    }
}